import React from 'react'
import {connect} from 'react-redux'
import { Form, Select, message, Switch, Button, Input, InputNumber } from 'antd';
import {messages} from "share/common";
import docTemplateService from "containers/financial-account/doc-template/doc-template-service";
const FormItem = Form.Item;
const Option = Select.Option;
const formItemLayout = {
  labelCol: {span: 8},
  wrapperCol: {span: 14},
};

class headerRule extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      record: {},
      codeList: [],
      journalList: [],
      saveLoading: false,
      setOfBooksId: '',
      isCombination: false,
      ruleList: [],
      isCuringField: false,
      isRuleDefineId: false
    }
  }

  getList = () => {
    const { setOfBooksId } = this.state;
    Promise.all([
      docTemplateService.getJournalList('HEAD',setOfBooksId),
      docTemplateService.getCodeList('HEAD',setOfBooksId),
      docTemplateService.getRuleList({type: 'HEAD', setOfBooksId})
    ]).then(res => {
      this.setState({
        journalList: res[0].data,
        codeList: res[1].data,
        ruleList: res[2].data
      });
    }).catch(() => {
      message.error(messages('financial-account.key15')/*系统异常*/);
    })
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.showSlideFrame === this.props.showSlideFrame)
      return;
    if (!nextProps.showSlideFrame) {
      this.props.form.resetFields();
      return !1;
    }
    this.props.form.resetFields();
    this.setState({
      record: nextProps.editRecord,
      setOfBooksId: nextProps.setOfBooksId,
      isCombination: nextProps.editRecord.isCombination ? nextProps.editRecord.isCombination : false,
      isCuringField: !!nextProps.editRecord.ruleDefineId,
      isRuleDefineId: !!nextProps.editRecord.curingField
    },() => {
      this.getList();
    });
  }

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err,values) => {
      if(!err){
        const { record, setOfBooksId } = this.state;
        const { user, tenant } = this.props;
        record.id && (values.id = record.id);
        values.tenantId = tenant.id;
        values.lineType = 1001;
        values.setOfBooksId = setOfBooksId;
        values.dataFormat = Number(values.dataFormat);
        let name = Object.keys(record).length > 0 ? 'updateTemplate' : 'addTemplate';
        this.setState({saveLoading: true});
        docTemplateService[name](values,user.userOID).then(() => {
          this.setState({saveLoading: false});
          this.props.close(true);
        }).catch(e => {
          this.setState({saveLoading: false});
          message.error(e.response.data.message);
        })
      }
    })
  };

  handleShowRuleDefineId = value => {
    this.setState({isRuleDefineId: !!value},() => {
      this.props.form.setFieldsValue({'ruleDefineId': undefined});
    });
  };

  handleShowCuringField = value => {
    this.setState({isCuringField: !!value},() => {
      this.props.form.setFieldsValue({'curingField': undefined});
    });
  };

  handleChangeCombination = (value) => {
    this.setState({isCombination: value},() => {
      this.props.form.setFieldsValue({curingField: undefined});
    });
  };

  render(){
    const { record, codeList, journalList, saveLoading, isCombination, ruleList, isCuringField, isRuleDefineId } = this.state;
    const { getFieldDecorator } = this.props.form;
    return(
      <div>
        <Form style={{marginTop:'10px'}}>
          <FormItem label={messages('common.sequence')/*序号*/} {...formItemLayout}>
            {getFieldDecorator('sequence', {
              rules: [{
                required: true, message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: record.sequence
            })(
              <InputNumber
                placeholder={messages('common.please.input')/*请输入*/}
                precision={0}
                min={0}
                step={1}
              />
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key16')/*凭证明细编码*/} {...formItemLayout}>
            {getFieldDecorator('ledgerCode', {
              rules: [{
                required: true, message: messages('common.please.select')/*请选择*/,
              },{
                max: 200, message: messages('financial-account.key141')/*最多输入200个字符*/
              }],
              initialValue: record.ledgerCode
            })(
              <Select placeholder={messages('common.please.select')/*请选择*/} disabled={record.ledgerCode ? true :false}>
                {
                  codeList.map(item => {
                    return <Option key={item} title={item}>{item}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key17')/*凭证明细名称*/} {...formItemLayout}>
            {getFieldDecorator('ledgerName', {
              rules: [{
                required: true, message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: record.ledgerName
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/}/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key151')/*接口编码*/} {...formItemLayout}>
            {getFieldDecorator('interfaceCode', {
              rules: [{
                required: true, message: messages('common.please.enter')/*请输入*/,
              }],
              initialValue: record.interfaceCode
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/}/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key18')/*凭证组合因素*/} {...formItemLayout}>
            {getFieldDecorator('isCombination',{
              initialValue: typeof record.isCombination === "boolean" ? record.isCombination : false,
              valuePropName: 'checked'
            })(
              <Switch onClick={value => this.handleChangeCombination(value)}/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key19')/*必输字段（视接口）*/} {...formItemLayout}>
            {getFieldDecorator('isNotEmpty',{
              initialValue: typeof record.isNotEmpty === "boolean" ? record.isNotEmpty : false,
              valuePropName: 'checked'
            })(
              <Switch/>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key20')/*固化字段标志*/} {...formItemLayout}>
            {getFieldDecorator('curingField', {
              initialValue: record.curingField || undefined
            })(
              <Select placeholder={messages('common.please.select')/*请选择*/}
                      onChange={this.handleShowRuleDefineId}
                      disabled={!isCombination || isCuringField} allowClear>
                {
                  journalList.map(item => {
                    return <Option key={item.curingField} title={item.curingField}>{item.curingField}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key165')/*规则字段标志*/} {...formItemLayout}>
            {getFieldDecorator('ruleDefineId', {
              initialValue: record.ruleDefine ? record.ruleDefine.id : undefined
            })(
              <Select placeholder={messages('common.please.select')/*请选择*/}
                      disabled={isRuleDefineId}
                      onChange={this.handleShowCuringField} allowClear>
                {
                  ruleList.map(item => {
                    return <Option key={item.id}>{item.ruleName}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem label={messages('financial-account.key193')/*字段格式*/} {...formItemLayout}>
            {getFieldDecorator('dataFormat', {
              initialValue: record.dataFormat ? record.dataFormat + '' : '1001'
            })(
              <Select placeholder={messages('common.please.select')}>
                <Option key={'1001'}>{messages('financial-account.key194')/*文本*/}</Option>
                <Option key={'1002'}>{messages('financial-account.key195')/*数字*/}</Option>
              </Select>
            )}
          </FormItem>
        </Form>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary"  onClick={this.handleSave} style={{margin:'0px 10px'}} loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    user: state.login.user,
    tenant: state.login.tenant
  }
}

const wrappedHeaderRule = Form.create()(headerRule);
export default connect(mapStateToProps)(wrappedHeaderRule);
